package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CategoryException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public SetmealDto findByIdWithSetmealAndCategoryName(Long id) {
        return setmealMapper.findByIdWithSetmealAndCategoryName(id);
    }

    @Override
    public Page<SetmealDto> pageByDto(Page<SetmealDto> dtoPage, String name) {
        return setmealMapper.pageByDto(dtoPage, name);
    }

    @Transactional
    @Override
    public void updateSetMelaDto(SetmealDto setmealDto) {
        this.saveOrUpdate(setmealDto);
        setmealDishService.lambdaUpdate()
                .eq(SetmealDish::getSetmealId, setmealDto.getId())
                .remove();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(sd -> sd.setSetmealId(setmealDto.getId()));
        setmealDishService.saveOrUpdateBatch(setmealDishes);
    }

    @Override
    public void deleteIds(Long[] ids) {
        Integer count = this.lambdaQuery()
                .in(Setmeal::getId, ids)
                .eq(Setmeal::getStatus, 1)
                .count();
        if (count > 0) {
            throw new CategoryException("套餐正在使用，删除失败");
        }
        this.removeByIds(Arrays.asList(ids));
        setmealDishService.lambdaUpdate().in(SetmealDish::getSetmealId, ids).remove();
    }

    @Transactional
    @Override
    public void updateSetMelaStatus(Integer status, Long[] ids) {
        this.lambdaUpdate()
                .in(Setmeal::getId, ids)
                .set(Setmeal::getStatus, status)
                .update(new Setmeal());
    }

    @Override
    public List<DishDto> getSetMealDishList(Long id) {
        return setmealMapper.getSetMealDishList(id);
    }
}
